package com.example.testjenkins.juc;

import cn.hutool.core.util.RandomUtil;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

public class CompletableFutureMail {

    static final List<Mail> mailList = Arrays.asList(
            new Mail("JD"),
            new Mail("TB"),
            new Mail("PDD")
    );

    public static void main(String[] args) {
        long l1 = System.currentTimeMillis();
        String bookName = "mysql";
        List<String> bookList1 = getBookList1(bookName);
        bookList1.forEach(System.out::println);

        System.out.println(System.currentTimeMillis() - l1);

        List<String> bookList2 = getBookList2(bookName);
        bookList2.forEach(System.out::println);

        System.out.println(System.currentTimeMillis() - l1);

    }

    private static List<String> getBookList1(String bookName) {
        return mailList.stream()
                .map(mail -> getFormat(mail, bookName))
                .collect(Collectors.toList());
    }

    private static String getFormat(Mail mail, String bookName) {
        return String.format("%s 的 《%s》 价格是：%.2f", mail.getName(), bookName, mail.calPrice(bookName));
    }

    private static List<String> getBookList2(String bookName) {
        return mailList.stream().map(mail -> CompletableFuture.supplyAsync(() -> getFormat(mail, bookName)))
                .collect(Collectors.toList())
                .stream()
                .map(cf -> cf.join())
                .collect(Collectors.toList());
    }
}

@Data
@Accessors(chain = true)
class Mail {
    private String name;

    public Mail(String name) {
        this.name = name;
    }

    public Double calPrice(String name) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return RandomUtil.randomDouble() + name.charAt(0);
    }
}
